package com.yuheadline.article.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dust.yuheadline.common.exception.CustomException;
import com.dust.yuheadline.common.utils.Result;
import com.yuheadline.article.mapper.ArticleImageMapper;
import com.yuheadline.article.mapper.ArticleMapper;
import com.yuheadline.article.service.ArticleImageService;
import com.yuheadline.article.service.ArticleService;
import com.yuheadline.article.util.ThreadLocalUtil;
import com.yuheadline.model.article.domain.Article;
import com.yuheadline.model.article.domain.ArticleImage;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author 高翔宇
 * @since 2025/4/19 周六 17:14
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class ArticleServiceImpl extends ServiceImpl<ArticleMapper, Article> implements ArticleService {
    private final ArticleMapper articleMapper;
    private final ArticleImageMapper articleImageMapper;
    private final ArticleImageService articleImageService;

    /**
     * 保存文章
     *
     * @param article 文章
     * @return 文章id
     */
    @Override
    public Result<Long> submitArticle(Article article) {
        if (article.getStatus() == null) {
            throw new CustomException(500, "文章状态不能为空");
        }
        if (article.getTitle() == null || article.getTitle().isEmpty()) {
            throw new CustomException(500, "文章标题不能为空");
        }
        String content = article.getContent();
        if (content == null || content.equals("<p><br></p>")) {
            throw new CustomException(500, "文章内容不能为空");
        }
        Long userId = ThreadLocalUtil.getUserId();
        if (userId == null) {
            throw new CustomException(401, "用户未登录");
        }
        Article selectByTempId = articleMapper.selectOne(new LambdaQueryWrapper<Article>().eq(Article::getTempId, article.getTempId()));
        if (article.getTempId() == null || selectByTempId != null) {
            throw new CustomException(500, "重复保存？");
        }
        Article newArticle = new Article();
        BeanUtils.copyProperties(article, newArticle);
        newArticle.setAuthorId(userId);
        LocalDateTime now = LocalDateTime.now();
        if (article.getId() == null) {
            newArticle.setCreateTime(now);
            newArticle.setUpdateTime(now);
            // 插入文章
            articleMapper.insert(newArticle);
            // 获取临时id对应的图片列表
            List<ArticleImage> articleImages = articleImageMapper.selectList(new LambdaQueryWrapper<ArticleImage>().eq(ArticleImage::getTempArticleId, article.getTempId()));
            articleImages.forEach(image -> {
                image.setArticleId(newArticle.getId());
                image.setTempArticleId(null);
                articleImageMapper.update(image, new LambdaQueryWrapper<ArticleImage>().eq(ArticleImage::getTempArticleId, article.getTempId()));
            });
        } else {
            newArticle.setUpdateTime(now);
            articleMapper.updateById(newArticle);
        }
        return new Result<Long>().success(newArticle.getId(), "保存成功！");
    }

    /**
     * 获取文章列表
     */
    @Override
    public Result<List<Article>> getArticleList() {
        Long userId = ThreadLocalUtil.getUserId();
        if (userId == null) {
            throw new CustomException(200, "用户未登录");
        }
        List<Article> articles = articleMapper.selectList(new LambdaQueryWrapper<Article>().eq(Article::getAuthorId, userId).orderByDesc(Article::getUpdateTime));
        return new Result<List<Article>>().success(articles, "查询成功！");
    }

    /**
     * 删除文章
     */
    @Override
    public Result<Void> deleteArticle(Long id) {
        Long userId = ThreadLocalUtil.getUserId();
        if (userId == null) {
            throw new CustomException(200, "用户未登录");
        }
        Article article = articleMapper.selectById(id);
        if (article == null) {
            throw new CustomException(200, "文章不存在");
        }
        if (!article.getAuthorId().equals(userId)) {
            throw new CustomException(200, "用户无权限删除该文章");
        }
        log.info("删除文章中的图片");
        articleImageService.deleteArticleImageByArticleId(id); // 一定要新删除图片再删除wenz
        articleMapper.deleteById(id);
        return new Result<Void>().success("删除成功！");
    }

    /**
     * 根据id获取文章
     */
    @Override
    public Result<Article> getArticleById(Long id) {
        Long userId = ThreadLocalUtil.getUserId();
        if (userId == null) {
            throw new CustomException(500, "用户未登录");
        }
        Article article = articleMapper.selectById(id);
        if (article == null) {
            throw new CustomException(500, "文章不存在");
        }
        if (!article.getAuthorId().equals(userId)) {
            throw new CustomException(500, "用户无权限查看该文章");
        }
        return new Result<Article>().success(article, "查询成功！");
    }
}
